<template>
  <div class="dict-page">
    <div class="dict-page-left" v-loading="leftLoading">
      <div class="dict-page-header">
        数据字典
        <ElButton v-if="auth.has('add')"  type="primary" link @click="onAddDict">添加</ElButton>
      </div>
      <ElScrollbar class="dict-page-body">
        <ElEmpty v-if="!dictList.length" />
        <div
          v-for="(item, index) in dictList"
          :key="index"
          class="dict-page-cell"
          :class="{ 'is-active': item.dictId === selectId }"
          @click="onSelect(item)"
        >
          {{ item.dictName }}
        </div>
      </ElScrollbar>
    </div>

    <ElScrollbar class="dict-page-main" v-loading="detailLoading">
      <div class="dict-page-right">
        <div class="dict-page-table-header">
          <div class="dict-page-title">字典内容</div>
          <ElButton v-if="auth.has('add')" type="primary" @click="onAddContent">新增</ElButton>
        </div>
        <ElEmpty v-if="!selectData" />
        <ElTable ref="table" :data="selectData">
          <ElTableColumn label="#" type="index" :width="50" />
          <ElTableColumn prop="val" label="值" />
          <ElTableColumn prop="name" label="名称" />
          <ElTableColumn v-if="selectNo === 'platform'" label="数据录入日期">
            <template #default="{ row }">
              {{ row.beforeDays ? `往前${ row.beforeDays }天` : '' }}
            </template>
          </ElTableColumn>
          <ElTableColumn prop="remark" label="其他" />
          <ElTableColumn fixed="right" label="操作" :width="180">
            <template #default="{ row }">
              <ElButton v-if="auth.has('move')" class="dict-page-table-handle" link type="primary" :icon="Rank">移动</ElButton>
              <ElButton v-if="auth.has('edit')"  link type="primary" @click="onEidt(row)">编辑</ElButton>
              <ElButton v-if="auth.has('delete')"  link type="primary" @click="onRemove(row)">删除</ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </ElScrollbar>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, shallowRef, nextTick, onBeforeUnmount } from 'vue'
import { getDataDictionaryList, getDataDictionary, removeDataDictionaryDetail, sortDataDictionaryDetail } from '../api'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus';
import { addDictDialog } from '../dialog/dictDialog'
import { dictDetailDialog, editDictDetailDialog, dictDetailNewDialog, editDictDetailNewDialog } from '../dialog/dictDetailDialog'
import { useAuth } from '@/utils/auth'
import { Rank } from '@element-plus/icons-vue'
import Sortable from 'sortablejs';
const auth = useAuth()

const leftLoading = ref(false)
const dictList = shallowRef([])

const detailLoading = ref(false)

const selectId = ref()
const selectNo = ref()
const selectData = ref([])

const sortable = shallowRef()
const table = ref()
const onCreateSortable = () => {
  const el = table.value.$el.querySelector('.el-table__body-wrapper .el-table__body tbody')
  sortable.value = new Sortable(el, {
    handle: '.dict-page-table-handle',
    animation: 150,
    ghostClass: 'blue-background-class',
    onUpdate: (event) => {
      const { oldIndex, newIndex } = event
      const max = Math.max(oldIndex, newIndex)
      const min = Math.min(oldIndex, newIndex)
      
      const list = [...selectData.value]
      const maxRow = list[max]
      const minRow = list[min]
      list.splice(max, 1, minRow)
      list.splice(min, 1, maxRow)
      const data = {
        dictId: selectId.value,
        dictDetailList: list
      }
      sortDataDictionaryDetail(data)
    }
  })
}
onBeforeUnmount(() => {
  sortable.value?.destroy()
})


const onSelect = (item) => {
  selectId.value = item.dictId
  selectNo.value = item.dictNo
  detailLoading.value = true
  getDataDictionary(item.dictId)
    .then(res => {
      selectData.value = res
      nextTick(() => {
        onCreateSortable()
      })
    })
    .finally(() => {
      detailLoading.value = false
    })
}

const getData  = () => {
  leftLoading.value = true
  getDataDictionaryList()
    .then(res => {
      dictList.value = res || []
      if (res.length) {
        onSelect(res[0])
      }
    }).finally(() => {
      leftLoading.value = false
    })
}

const onAddContent = async () => {
  const methods = selectNo.value === 'platform'
    ? dictDetailNewDialog.open({ row: { dictId: selectId.value, dictNo: selectNo.value } })
    : dictDetailDialog.open({ row: { dictId: selectId.value, dictNo: selectNo.value } })
  await methods
  onSelect({ dictId: selectId.value, dictNo: selectNo.value })
}

const onEidt = async row => {
  const methods = selectNo.value === 'platform'
    ? editDictDetailNewDialog.open({ row })
    : editDictDetailDialog.open({ row })
  await methods
  onSelect({ dictId: selectId.value, dictNo: selectNo.value })
}

const onRemove = async row => {
  await ElMessageBox.confirm('是否确定删除？', '提示')
  await removeDataDictionaryDetail([row.dictDetailId])
  ElMessage.success('操作成功')
  onSelect({ dictId: selectId.value, dictNo: selectNo.value })
}

const onAddDict = async () => {
  await addDictDialog.open()
  getData()
}

onMounted(() => {
  getData()
})

defineOptions({
  name: 'DataDictionary'
})
</script>

<style scoped lang="scss">
.dict-page {
  flex: 1;
  box-sizing: border-box;
  height: 100%;
  display: flex;
  padding: 20px 15px;
  background: var(--el-color-white);

  &-left {
    box-sizing: border-box;
    width: 280px;
    border-radius: 4px;
    border: 1px solid #F0F0F0;
    border-collapse: collapse;
  }

  &-header {
    box-sizing: border-box;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #F2F6FF;
    height: 50px;
    font-family: PingFangHK-Medium;
    font-weight: 500;
    font-size: 16px;
    color: #333333;
  }

  &-body {
    box-sizing: border-box;
    height: calc(100vh - 218px);
  }

  &-cell {
    box-sizing: border-box;
    height: 50px;
    display: flex;
    align-items: center;
    padding: 0 19px;
    font-family: PingFangHK-Regular;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    border-top: 1px solid #F0F0F0;
    cursor: pointer;

    &.is-active {
      font-family: PingFangHK-Medium;
      font-weight: 500;
      font-size: 14px;
      color: #FFFFFF;
      background: #094DB2;
    }
  }

  &-right {
    margin-left: 20px;
  }

  &-main {
    flex-grow: 1;
    height: calc(100vh - 170px);
  }

  &-table-header {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  &-title {
    font-family: PingFangHK-Medium;
    font-weight: 500;
    font-size: 16px;
    color: #333333;
  }
}
</style>
